package com.atguigu.yygh.user.service.impl;

import com.atguigu.yygh.client.DictFeignClient;
import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.common.handler.JwtHelper;
import com.atguigu.yygh.enums.AuthStatusEnum;
import com.atguigu.yygh.enums.StatusEnum;
import com.atguigu.yygh.model.user.Patient;
import com.atguigu.yygh.model.user.UserInfo;
import com.atguigu.yygh.user.mapper.PatientMapper;
import com.atguigu.yygh.user.mapper.UserInfoMapper;
import com.atguigu.yygh.user.service.UserInfoService;
import com.atguigu.yygh.vo.user.LoginVo;
import com.atguigu.yygh.vo.user.UserInfoQueryVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author xin Zhou
 * @since 2024-01-27
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private PatientMapper patientMapper;

    @Autowired
    private DictFeignClient dictFeignClient;
//    登录功能
    @Override
    public Map<String, Object> login(LoginVo loginVo) {
//        1.获取用户输入的手机号和验证码信息
        String phone = loginVo.getPhone();
        String code = loginVo.getCode();
//        2.对接收到的手机号和验证码做非空验证
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)){
            throw  new YyghException(20001,"手机号或者验证码信息有误,请重新填写");
        }
//        3.对验证码做进一步确认
        Integer redisCode = (int) redisTemplate.opsForValue().get(phone);
        if (StringUtils.isEmpty(redisCode)){
            throw new YyghException(20001,"手机验证码有误");
        }
        UserInfo userInfo =new UserInfo();
        String openid = loginVo.getOpenid();
        if (StringUtils.isEmpty(openid)){
 //        4.手机号是否是首次登录,如果是首次登录,就先往表中注入当前用户信息
            QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("phone",phone);
             userInfo = baseMapper.selectOne(queryWrapper);
//        如果是首次登录则先创建一个UserInfo 之后注入手机号 在表中添加数据
            if (userInfo == null){
                userInfo = new UserInfo();
                userInfo.setPhone(phone);
                baseMapper.insert(userInfo);
                userInfo.setStatus(1);

            }

//        5.验证用户的Status的状态
            if (userInfo.getStatus() == 0){
                throw  new YyghException(20001,"用户正在锁定无法登录");
            }

        }else { //微信强制绑定手机号
            QueryWrapper<UserInfo> openIdQuery = new QueryWrapper<>();
            openIdQuery.eq("phone",phone);
            userInfo = baseMapper.selectOne(openIdQuery);

            QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("phone",phone);
            UserInfo userInfo2= baseMapper.selectOne(queryWrapper);

            if (userInfo2 == null){
                userInfo.setPhone(phone);
                userInfo.setStatus(1);
                baseMapper.updateById(userInfo);
            }else {
                QueryWrapper<UserInfo> queryWrapper1 = new QueryWrapper<>();
                queryWrapper1.eq("openid",openid);
                UserInfo userInfo3 = baseMapper.selectOne(queryWrapper1);
                userInfo.setOpenid(userInfo3.getOpenid());
                userInfo.setNickName(userInfo3.getNickName());
                baseMapper.updateById(userInfo);
                baseMapper.deleteById(userInfo3.getId());
            }
        }

//        6.返回用户信息
        Map<String, Object> result = new HashMap<>();
        String name = userInfo.getName();
        if(StringUtils.isEmpty(name)) {
            name = userInfo.getNickName();
        }
        if(StringUtils.isEmpty(name)) {
            name = userInfo.getPhone();
        }
        result.put("name",name);

        String token = JwtHelper.createToken(userInfo.getId(), name);
//        System.out.println("token = " + token);
        result.put("token",token);
        return result;
    }

    /*
    * 根据用户Id获取用户信息
    * */
    @Override
    public UserInfo getuserInfo(Long userId) {
        UserInfo userInfo = baseMapper.selectById(userId);
        userInfo.getParam().put("authStatusString",
                AuthStatusEnum.getStatusNameByStatus(userInfo.getAuthStatus()));
        return userInfo;
    }

//  分页查询
    @Override
    public Page<UserInfo> getUserInfoPage(Integer pageNum, Integer limit, UserInfoQueryVo userInfoQueryVo) {
        Page<UserInfo> page = new Page<>(pageNum,limit);
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();

        String keyword = userInfoQueryVo.getKeyword();
        if (!StringUtils.isEmpty(userInfoQueryVo.getKeyword())){
            queryWrapper.like("name",userInfoQueryVo.getKeyword()).or().eq("phone",userInfoQueryVo.getKeyword());
        }
        if (!StringUtils.isEmpty(userInfoQueryVo.getStatus())){
            queryWrapper.eq("status",userInfoQueryVo.getStatus());
        }
        if (!StringUtils.isEmpty(userInfoQueryVo.getAuthStatus())){
            queryWrapper.eq("auth_status",userInfoQueryVo.getAuthStatus());
        }
        if (!StringUtils.isEmpty(userInfoQueryVo.getCreateTimeBegin())){
            queryWrapper.gt("create_time",userInfoQueryVo.getCreateTimeBegin());
        }
        if (!StringUtils.isEmpty(userInfoQueryVo.getCreateTimeEnd())){
            queryWrapper.lt("create_time",userInfoQueryVo.getCreateTimeEnd());
        }
        Page<UserInfo> resultPage = baseMapper.selectPage(page, queryWrapper);
        resultPage.getRecords().stream().forEach(item->{
            this.packageUserInfo(item);
        });
        return resultPage;
    }

//    根据Id修改用户状态信息
    @Override
    public void updateStatus(Long id, Integer status) {
        if (status ==0 || status ==1){
            UserInfo userInfo = new UserInfo();
//            利用mybatis_plus 进行直接修改数据
            userInfo.setId(id);
            userInfo.setStatus(status);
            baseMapper.updateById(userInfo);

        }
    }
//    查看用户的详细信息(查询用户信息和就诊人信息)
    @Override
    public Map<String, Object> detail(Long id) {
//        查询当前用户信息
        UserInfo userInfo = baseMapper.selectById(id);

//        查询当前用户的就诊人信息
        QueryWrapper<Patient> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",id);
        List<Patient> patientList = patientMapper.selectList(queryWrapper);
//        数据进行封装
        patientList.stream().forEach(this::packagePatient);

//        封装到Map数组中
        Map<String, Object> map = new HashMap<>();
        map.put("userInfo",userInfo);
        map.put("patients",patientList);
        return map;
    }

//    对用户信息进行封装
    private void packageUserInfo(UserInfo item) {
        Integer authStatus = item.getAuthStatus();
        Integer status = item.getStatus();

        item.getParam().put("statusString", StatusEnum.getStatusStringbyStatus(status));
        item.getParam().put("authStatusString",AuthStatusEnum.getStatusNameByStatus(authStatus));
    }

//    对就诊人信息进行封装
    private void packagePatient(Patient item) {
//        在字典里查询数据,code --> 文字
        String result = dictFeignClient.getNameByValue(Long.parseLong(item.getCertificatesType()));
        item.getParam().put("certificatesTypeString",result);

        String provinceString = dictFeignClient.getNameByValue(Long.parseLong(item.getProvinceCode()));
        String cityString = dictFeignClient.getNameByValue(Long.parseLong(item.getCityCode()));
        String districtString = dictFeignClient.getNameByValue(Long.parseLong(item.getDistrictCode()));

        item.getParam().put("fullAddress",provinceString+"/"+cityString+"/"+districtString+"/"+item.getAddress());
    }
}
